package org.springframework.cloud.netflix.feign.ribbon;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.Setter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Will be injected into {@link }
 */
public class CoreCanaryFilter extends OncePerRequestFilter implements RequestInterceptor {
    static final CoreCanaryFilter INSTANCE = new CoreCanaryFilter();
    private static final ThreadLocal<Map<String, String>> HEADERS =
        ThreadLocal.withInitial(HashMap::new);

    private CoreCanaryFilter() {
    }

    @Setter
    private CanaryProperties canary;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        canary.getHeaders().stream().filter(header -> request.getHeader(header) != null)
            .forEach(header -> HEADERS.get().put(header, request.getHeader(header)));
    }

    public static Map<String, String> headers() {
        return HEADERS.get();
    }

    public static void headers(Map<String, String> headers) {
        HEADERS.set(headers);
    }

    @Override
    public void apply(RequestTemplate template) {
        HEADERS.get().forEach(template::header);
    }
}
